<template>
  <div class="main-content">
    <div class="login-container">
      <a-form
        id="formLogin"
        ref="formLogin"
        class="user-layout-login"
        :form="form"
        style="width:320px;text-align:center;margin-left:50px;"
        @submit="handleSubmit"
      >
        <a-tabs :activeKey="customActiveKey" @change="handleTabClick">
          <a-tab-pane key="tab1">
            <span slot="tab" style="margin-bottom:30px;text-align:left;">
              <a-icon
                v-if="customActiveKey === 'tab1'"
                :component="AccountIcon01"
                style="fontSize: 24px;margin-top:34px;color:#c8c8c8"
              />
              <a-icon v-else :component="AccountIcon" style="fontSize: 24px;margin-top:34px;" />
              账号登录
            </span>
            <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 0px;" message="账户或密码错误" />
            <a-row :gutter="24">
              <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                <a-form-item style="margin-bottom:0px;">
                  <a-input
                    v-decorator="[
                      'username',
                      {
                        rules: [{ required: true, message: '请输入用户名' }, { validator: handleUsernameOrEmail }],
                        validateTrigger: 'change',
                        initialValue: ''
                      }
                    ]"
                    size="large"
                    type="text"
                    placeholder="请输入用户名"
                    style="margin-top:12px;"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                <a-form-item style="margin-bottom:0px;">
                  <a-input-password
                    v-decorator="[
                      'password',
                      {
                        rules: [{ required: true, message: '请输入密码' }],
                        validateTrigger: 'blur',
                        initialValue: ''
                      }
                    ]"
                    style="text-align:left;"
                    size="large"
                    placeholder="请输入登录密码"
                  >
                  </a-input-password>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :xl="14" :lg="14" :md="14" :sm="14" :xs="14">
                <a-form-item style="margin-bottom:0px;">
                  <a-input
                    v-decorator="['verification', { rules: [{ required: true, message: '请输入验证码' }] }]"
                    size="large"
                    type="text"
                    placeholder="请输入验证码"
                    style="width:220px"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :xl="10" :lg="10" :md="10" :sm="10" :xs="10">
                <img :src="'data:image/png;base64,' + captchaImg" alt="" class="captchaImg" @click="refreshCaptch()" />
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="tab2">
            <span slot="tab">
              <a-icon v-if="customActiveKey === 'tab2'" :component="PhoneIcon01" style="fontSize: 24px;" />
              <a-icon v-else :component="PhoneIcon" style="fontSize: 24px;" />
              手机号登录
            </span>
            <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" message="账户或密码错误" />
            <a-row :gutter="24">
              <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                <a-form-item style="margin-bottom:0px;">
                  <a-input
                    v-decorator="[
                      'mobile',
                      {
                        rules: [
                          { required: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ },
                          { validator: this.handlePhoneCheck }
                        ],
                        validateTrigger: ['change', 'blur']
                      }
                    ]"
                    size="large"
                    type="text"
                    placeholder="请输入手机号"
                    style="margin-top:12px;"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="display:inline-block;">
              <a-col :xl="14" :lg="14" :md="14" :sm="14" :xs="14">
                <a-form-item style="margin-bottom:0px;display:inline-block;">
                  <a-input
                    v-decorator="['captcha', { rules: [{ required: true, message: '请输入验证码' }] }]"
                    size="large"
                    type="text"
                    placeholder="请输入手机验证码"
                    style="width:220px;"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :xl="10" :lg="10" :md="10" :sm="10" :xs="10">
                <a-button
                  size="large"
                  type="primary"
                  class="getCaptcha"
                  :disabled="state.smsSendBtn"
                  @click.stop.prevent="getCaptcha"
                  v-text="(!state.smsSendBtn && '获取验证码') || state.time + ' s'"
                  >获取验证码</a-button
                >
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
        <a-row class="button_login">
          <a-button
            style="width: 320px;height: 48px;background-color: #33b0ed;border-radius: 2px;"
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="state.loginBtn"
            :disabled="state.loginBtn"
            >登录</a-button
          >
          <a herf class="login-tips" style="float:left;" @click="gotoRegister()">立即注册</a>
          <a herf class="login-tips" style="float:right;" @click="gotoForgetPassword()">忘记密码？</a>
        </a-row>
      </a-form>
    </div>
  </div>
</template>

<script>
import { getSmsCaptcha } from '@/api/login'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { captcha } from '@/api/login'
import PhoneIcon from '@/assets/svg/PhoneLogin.svg'
import AccountIcon from '@/assets/svg/AccountLogin.svg'
import PhoneIcon01 from '@/assets/svg/PhoneLogin01.svg'
import AccountIcon01 from '@/assets/svg/AccountLogin01.svg'
export default {
  data() {
    return {
      AccountIcon,
      PhoneIcon,
      AccountIcon01,
      PhoneIcon01,
      cur: 0,
      visibilityToggle: false,
      customActiveKey: 'tab1',
      loginBtn: false,
      loginType: 0,
      isLoginError: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
      captchaImg: null,
      uuid: ''
    }
  },
  created() {
    this.imageCaptcha()
  },
  methods: {
    ...mapActions(['Login', 'LoginMobile', 'Logout']),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    imageCaptcha() {
      captcha({})
        .then(response => {
          this.captchaImg = response.data.captcha || null
          this.uuid = response.data.uuid || ''
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    refreshCaptch() {
      this.imageCaptcha()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit(e) {
      const that = this
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login,
        LoginMobile
      } = this

      state.loginBtn = true
      const validateFieldsKey =
        customActiveKey === 'tab1' ? ['username', 'password', 'verification'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = {}
          // 账号密码登陆和手机登陆分为两个接口
          if (customActiveKey === 'tab1') {
            loginParams.username = values.username
            loginParams.password = values.password
            loginParams.uuid = that.uuid
            loginParams.verCode = values.verification
            Login(loginParams)
              .then(res => this.loginSuccess(res))
              .catch(err => this.requestFailed(err))
              .finally(() => {
                state.loginBtn = false
              })
          } else {
            loginParams.mobile = values.mobile
            loginParams.captcha = values.captcha
            LoginMobile(loginParams)
              .then(res => this.loginSuccess(res))
              .catch(err => this.requestFailed(err))
              .finally(() => {
                state.loginBtn = false
              })
          }
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    handlePhoneCheck(rule, value, callback) {
      console.log('handlePhoneCheck, rule:', rule)
      console.log('handlePhoneCheck, value', value)
      console.log('handlePhoneCheck, callback', callback)

      callback()
    },

    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        $message,
        $notification
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = $message.loading('验证码发送中..', 0)

          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500)
              console.log(res)
              $notification['success']({
                message: '提示',
                description: '验证码获取成功,请及时查看!',
                duration: 8
              })
            })
            .catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    handleChange(e) {
      this.checkNick = e.target.checked
      this.$nextTick(() => {
        this.form.validateFields(['nickname'], { force: true })
      })
    },
    loginSuccess(res) {
      console.log(res)
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    },
    // 注册
    gotoRegister() {
      this.$router.push('register')
    },
    // 找回密码
    gotoForgetPassword() {
      this.$router.push('forget-password')
    }
  }
}
</script>

<style lang="less" scoped>
.main-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-container {
  width: 420px;
  min-height: 410px;
  background-color: #feffff;
  box-shadow: 2px 1px 18px -2px #e0ecff;
  border-radius: 1px;
  // #formLogin {
  //   min-height: 410px;
  // }
  /deep/.ant-tabs-nav .ant-tabs-tab {
    margin: 0 0 0 0;
    padding: 12px 26px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 26px;
    letter-spacing: 0px;
    font-size: 16px;
    color: #333333;
  }
  /deep/.ant-tabs-ink-bar.ant-tabs-ink-bar-animated {
    width: 160px;
    height: 3px;
    background-color: #33b0ed;
  }
  /deep/.ant-tabs-nav .ant-tabs-tab .anticon {
    color: #c8c8c8;
  }
  /deep/.ant-tabs-nav .ant-tabs-tab-active .anticon {
    color: #33b0ed;
  }
  /deep/.ant-input-lg {
    width: 320px;
    height: 42px;
    border-radius: 2px;
    border: solid 1px #e5e6e9;
    margin-bottom: 12px;
    font-size: 14px;
  }
  /deep/ .ant-input {
    position: relative;
    text-align: left;
  }
  /deep/ .ant-form-explain {
    text-align: left;
  }
  /deep/.getCaptcha.ant-btn-primary {
    border: none;
    width: 88px;
    height: 42px;
    background-color: #f2f5f8;
    border-radius: 2px;
    margin-left: 28px;
    font-size: 12px;
    color: rgba(51, 51, 51, 0.8);
  }
  /*密码是否显示*/
  /deep/ .ant-input-suffix {
    color: #8ea3d1;
    right: -12px;
    svg {
      width: 24px;
      height: 18px;
      display: none;
    }

    /*输入框提示*/
    /deep/ .little {
      font-size: 14px;
      color: #8ea3d1;
    }
    /*form表单每一项*/
    /deep/ .ant-form-item {
      margin-bottom: 0px;
    }
    .ant-row {
      margin-bottom: 25px;
    }
    /*输入框的文字边距*/
    /deep/ .ant-input-prefix {
      left: 0;
    }
    .tilte {
      font-size: 22px;
      margin-bottom: 18px;
      color: #b6caf6;
    }
    .account {
      width: 240px;
    }
  }
  .captchaImg {
    width: 90px;
    height: 38px;
    float: right;
  }
  .captchaImg:hover {
    cursor: pointer;
  }
  .login-tips {
    margin-top: 12px;
    width: 60px;
    height: 12px;
    font-size: 12px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 12px;
    letter-spacing: 0px;
    color: #333333;
  }
  .button_login {
    margin-top: 18px;
  }
}
</style>
